import {
  Table as AntdTable,
  Button,
  Form,
  Input,
  Modal,
  Select,
  Switch,
  message,
} from "antd";
import Mock from "mockjs";
import React, { useEffect, useState } from "react";
import request from "umi-request";
import CascadingSelect from "../Select/Cascader";
import "./schoolTable.scss";

const response = await request.get("/api/school");

const mockData = Mock.mock({
  "list|100": [
    {
      "id|+1": 1,
      name: "@cname",
      age: "@integer(18, 60)",
      address: "@county(true)",
      "state|1": ["true", "false"],
    },
  ],
});

const provinceData = ["河北", "北京"];

const cityData = {
  河北: ["Hangzhou", "Ningbo", "Wenzhou"],
  北京: ["Nanjing", "Suzhou", "Zhenjiang"],
};
type CityName = keyof typeof cityData;

interface User {
  id: number;
  name: string;
  age: number;
  address: string;
}

interface TableProps {
  dataSource: User[];

  onCreate?: (user: User) => void;
  onUpdate?: (user: User) => void;
  onDelete?: (id: number) => void;
  onSelectChange?: (selectedRowKeys: number[]) => void;
}

const Table: React.FC<TableProps> = ({
  dataSource,
  onCreate = () => {},
  onUpdate = () => {},
  onDelete = () => {},
  onSelectChange = () => {},
}) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 7,
    total: dataSource.length,
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [states, useStates] = useState(response);
  console.log(states);

  useEffect(() => {
    // 模拟异步请求数据
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  }, [pagination.current, pagination.pageSize]);

  const [cities, setCities] = useState(cityData[provinceData[0] as CityName]);
  const [secondCity, setSecondCity] = useState(
    cityData[provinceData[0] as CityName][0]
  );

  const handleProvinceChange = (value: CityName) => {
    setCities(cityData[value]);
    setSecondCity(cityData[value][0]);
  };

  const onSecondCityChange = (value: CityName) => {
    setSecondCity(value);
  };

  const handleCreate = () => {
    setVisible(true);
  };

  const handleUpdate = (record: User) => {
    setVisible(true);
    form.setFieldsValue(record); // 设置表单的初始值
    form.setFieldsValue({ id: record.id }); // 在表单中增加id字段，以便区分添加和更新操作
  };

  const handleDelete = (id: number) => {
    Modal.confirm({
      title: "确认删除？",
      onOk: () => {
        onDelete(id);
        message.success("删除成功");
      },
    });
  };

  const handleOk = () => {
    form.validateFields().then((values) => {
      const user = {
        ...values,
      };
      if (user.id) {
        // 如果id存在，则为更新操作
        onUpdate(user);
        message.success("编辑成功");
      } else {
        user.id = dataSource.length + 1; // 不存在则视为添加，并生成新id
        onCreate(user);
        message.success("创建成功");
      }
      form.resetFields();
      setVisible(false);
    });
  };

  const handleCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  const handlePageChange = (current: number, pageSize?: number) => {
    setPagination({
      current,
      pageSize: pageSize || pagination.pageSize,
      total: dataSource.length,
    });
  };

  const handlePageSizeChange = (current: number, pageSize: number) => {
    setPagination({
      current,
      pageSize,
      total: dataSource.length,
    });
  };

  const handleSelectionChange = (selectedRowKeys: any[]) => {
    setSelectedRowKeys(selectedRowKeys);
    onSelectChange(selectedRowKeys);
  };

  const columns: any = [
    {
      title: "ID",
      dataIndex: "id",
      align: "center", // 设置表头居中对齐
      render: (text: any) => <div style={{ textAlign: "center" }}>{text}</div>,
    },
    {
      title: "姓名",
      dataIndex: "name",
      width: "20%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (text: any) => <div style={{ textAlign: "center" }}>{text}</div>,
    },
    {
      title: "年龄",
      dataIndex: "age",
      width: "20%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (text: any) => <div style={{ textAlign: "center" }}>{text}</div>,
    },
    {
      title: "地址",
      dataIndex: "address",
      width: "20%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (text: any) => <div style={{ textAlign: "center" }}>{text}</div>,
    },
    {
      title: "状态",
      width: "20%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (text: any) => (
        <div style={{ textAlign: "center" }}>
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
            defaultChecked={true}
          />
        </div>
      ),
    },
    {
      title: "操作",
      width: "20%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (_: any, record: User) => (
        <>
          <Button
            type="link"
            onClick={() => handleCreate}
            className="handleUpdate"
          >
            添加城市
          </Button>
          <Button
            type="link"
            onClick={() => handleUpdate(record)}
            className="handleUpdate"
          >
            城市管理
          </Button>
          <Button
            type="link"
            danger
            onClick={() => handleDelete(record.id)}
            className="handleDelete"
            style={{ color: "white" }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <div
      className="fesgguyagguyka"
      style={{ fontSize: "12px", lineHeight: 1.5 }}
    >
      <div style={{ marginBottom: 16, fontSize: "12px", lineHeight: 1.5 }}>
        <div className="select">
          <CascadingSelect></CascadingSelect>
        </div>
        <Button type="primary" onClick={handleCreate} className="handleCreate">
          添加城市
        </Button>
        <Button
          type="primary"
          danger
          disabled={selectedRowKeys.length === 0}
          style={{ marginLeft: 8 }}
          onClick={() => {
            Modal.confirm({
              title: "确认删除？",
              onOk: () => {
                selectedRowKeys.forEach((id) => onDelete(id));
                setSelectedRowKeys([]);
                message.success("删除成功");
              },
            });
          }}
        >
          批量删除
        </Button>
      </div>
      <AntdTable
        scroll={{ x: "max-content" }}
        style={{ fontSize: "12px", lineHeight: 1.5 }}
        rowKey="id"
        dataSource={dataSource.slice(
          (pagination.current - 1) * pagination.pageSize,
          pagination.current * pagination.pageSize
        )}
        columns={columns}
        loading={loading}
        pagination={{
          ...pagination,
          onChange: handlePageChange,
          onShowSizeChange: handlePageSizeChange,
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: handleSelectionChange,
        }}
      />
      <Modal
        title="城市管理"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
          <Form.Item name="id" noStyle>
            <Input type="hidden" />
          </Form.Item>
          <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="age" label="年龄" rules={[{ required: true }]}>
            <Input type="number" />
          </Form.Item>
          <Form.Item name="address" label="地址" rules={[{ required: true }]}>
            <Select style={{ width: "100%" }} popupMatchSelectWidth>
              <Select.Option value="北京市">北京市</Select.Option>
              <Select.Option value="上海市">上海市</Select.Option>
              <Select.Option value="广州市">广州市</Select.Option>
              <Select.Option value="深圳市">深圳市</Select.Option>
              <Select.Option value="杭州市">杭州市</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default () => {
  const [dataSource, setDataSource] = useState<User[]>(response);

  const handleCreate = (user: User) => {
    setDataSource([...dataSource, user]);
  };

  const handleUpdate = (user: User) => {
    setDataSource(
      dataSource.map((item) => (item.id === user.id ? user : item))
    );
  };

  const handleDelete = (id: number) => {
    setDataSource(dataSource.filter((item) => item.id !== id));
  };

  const handleSelectChange = (selectedRowKeys: number[]) => {
    console.log(selectedRowKeys);
  };

  return (
    <div>
    <Table
      dataSource={dataSource}
      onCreate={handleCreate}
      onUpdate={handleUpdate}
      onDelete={handleDelete}
      onSelectChange={handleSelectChange}
    />
    </div>
  );
};
